package cn.xiaopengstack.domain.activity.service.discount;

import cn.xiaopengstack.domain.activity.model.dto.DiscountCalculateDTO;
import cn.xiaopengstack.domain.tag.repository.ITagRepository;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @author jiangyangang
 */
@Slf4j
public abstract class AbstractDiscountCalculateService implements IDiscountCalculateService {

    @Resource
    private ITagRepository tagRepository;

    @Override
    public BigDecimal calculate(DiscountCalculateDTO calculateDTO) {
        // 人群过滤
        if (isNeedFilterUser(calculateDTO.getGroupBuyDiscount().getTagId(), calculateDTO.getUserId())) {
            return calculateDTO.getOriginalPrice();
        }

        // 折扣计算
        return doCalculate(calculateDTO);
    }

    private boolean isNeedFilterUser(String tagId, String userId) {
        return tagRepository.isTagCrowdRange(tagId, userId);
    }

    protected abstract BigDecimal doCalculate(DiscountCalculateDTO calculateDTO);

    /**
     * 转换最小价格为1分钱
     * @param price
     * @return
     */
    protected BigDecimal coverMinPrice(BigDecimal price, BigDecimal minPrice){
        return price.compareTo(minPrice) < 0 ? minPrice : price;
    }
}
